import type { RouteRecordRaw } from 'vue-router'
import { LOGIN_URL } from '@/constants/global'
import { useRouteStore } from '@/stores'
import { routes } from '@/routers/modules/index'

// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob('@/views/**/*.vue')
/**
 * @description 初始化动态路由，并扁平化菜单列表
 */
export function initDynamicRouter(router) {
  const authStore = useRouteStore()

  try {
    authStore.setMenuList(routes)

    // 添加动态路由

    authStore.flatMenuList.forEach((item) => {
      item.children && delete item.children
      if (item.component && typeof item.component === 'string')
        item.component = modules[`/src/views${item.component}.vue`]
      if (item.meta.isFull)
        router.addRoute(item as unknown as RouteRecordRaw)
      else router.addRoute('layout', item as unknown as RouteRecordRaw)
    })
  }
  catch (error) {
    // 当按钮 || 菜单请求出错时，重定向到登陆页
    console.error(error)
    router.replace(LOGIN_URL)
    // return Promise.reject(error)
  }
}
